package javaCode;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * Created by lxy_920912 on 27/04/2017.
 */
public class LeetCode15 {
    public List<List<Integer>> threeSum(int[] nums) {

        List<List<Integer>> result  = new ArrayList<>();
        Arrays.sort(nums);
        int len = nums.length;
        for(int i = 0;i < nums.length-2;i++){
            int target = nums[i];
            int j = i+1;
            int k = len-1;
            while(j < k){
                if(nums[j]+nums[k] == -target){
                    List<Integer> temp = new ArrayList<>();
                    temp.add(target);
                    temp.add(nums[j]);
                    temp.add(nums[k]);
                    result.add(temp);
                    while(nums[j] == nums[j+1]){
                        j++;

                    }
                    while (nums[k] == nums[k-1]){
                        k--;
                    }
                    j++;
                    k--;
                }else if(nums[j] + nums[k] < -target){
                    while(nums[j] == nums[j+1]){
                        j++;
                    }
                    j++;
                }else{
                    while(nums[k] == nums[k-1]){
                        k--;
                    }
                }
            }

        }
        return  result;
    }
}
